
namespace SharpTalk.Core.Services
{
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Xml;
    using System.Text;

    public sealed class Serializer
    {
        public static T Load<T>(string file) where T : class
        {
            if (File.Exists(file))
                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    var br = new BinaryReader(fs);
                    byte[] encryptedData = br.ReadBytes((int)fs.Length);
                    using(var ms = new MemoryStream( SecurityServices.Decrypt(encryptedData) ))
                    {
                        var ser = new BinaryFormatter();
                        var data = ser.Deserialize(ms);
                        if (data != null)
                            return (T)data;    
                    }
                }
            return default(T);
        }

        public static void Save<T>(string file, T obj) where T : class
        {
            if (obj == null || string.IsNullOrEmpty(file)) return;

            using (var ms  = new MemoryStream())
            using (var fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                var ser = new BinaryFormatter();
                ser.Serialize(ms, obj);
                byte[] encryptedData = SecurityServices.Encrypt(ms.GetBuffer());
                fs.Write(encryptedData, 0, encryptedData.Length);
            }
        }

        //public static void SaveAsXml<T>(string file, T obj, bool append)
        //    where T : class 
        //{
        //    if(obj == null || string.IsNullOrEmpty(file)) return;
        //    using(var fs = new FileStream(file, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read ,4096) )
        //    {
        //        var xser = new System.Xml.Serialization.XmlSerializer(typeof (T));
        //        xser.Serialize(fs,obj);
        //    }
        //}
    }
}